package edu.del.teamknowledgebase.service.email.impl;

import edu.del.teamknowledgebase.common.constant.cache.CacheKeyConstant;
import edu.del.teamknowledgebase.service.email.EmailService;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {

    private final JavaMailSender mailSender;

    private final StringRedisTemplate redisTemplate;

    // 5分钟过期
    private static final long CODE_EXPIRE_TIME = 5;

    @Override
    public boolean sendVerificationCode(String to, String code) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom("<2791786903@qq.com>");
            helper.setTo(to);
            helper.setSubject("【团队知识库】验证码");

            // HTML邮件内容
            String content = String.format(
                    "<div style='padding: 20px; background-color: #f5f5f5;'>" +
                            "  <div style='max-width: 600px; margin: 0 auto; background-color: white; padding: 30px; border-radius: 10px;'>" +
                            "    <h2 style='color: #1890ff; text-align: center;'>团队知识库</h2>" +
                            "    <p style='font-size: 16px;'>您好！</p>" +
                            "    <p style='font-size: 14px;'>您正在进行邮箱验证，验证码为：</p>" +
                            "    <div style='text-align: center; margin: 20px 0;'>" +
                            "      <span style='font-size: 32px; font-weight: bold; color: #1890ff; letter-spacing: 5px;'>%s</span>" +
                            "    </div>" +
                            "    <p style='font-size: 14px; color: #666;'>验证码有效期为5分钟，请勿泄露给他人。</p>" +
                            "    <p style='font-size: 14px; color: #666;'>如非本人操作，请忽略此邮件。</p>" +
                            "    <hr style='margin: 30px 0; border: none; border-top: 1px solid #eee;'>" +
                            "    <p style='font-size: 12px; color: #999; text-align: center;'>此邮件由系统自动发送，请勿回复。</p>" +
                            "  </div>" +
                            "</div>",
                    code
            );
            helper.setText(content, true);

            // 发送邮件
            mailSender.send(message);

            // 将验证码存入Redis
            String key = String.format(CacheKeyConstant.VERIFICATION_CODE_KEY_PREFIX,to);
            redisTemplate.opsForValue().set(key, code, CODE_EXPIRE_TIME, TimeUnit.MINUTES);

            log.info("邮件验证码发送成功: email={}, code={}", to, code);
            return true;
        } catch (MessagingException e) {
            log.error("邮件验证码发送失败：email={}，error={}", to, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean verifyCode(String email, String code) {
        String key = String.format(CacheKeyConstant.VERIFICATION_CODE_KEY_PREFIX, email);
        String cacheCode = redisTemplate.opsForValue().get(key);

        if (cacheCode == null) {
            log.warn("验证码不存在或已过期， email={}", email);
            return false;
        }

        boolean isValid = cacheCode.equals(code);
        if (isValid) {
            // 验证成功后删除验证码
            redisTemplate.delete(key);
            log.info("验证码验证成功， email={}", email);
        } else {
            log.warn("邮箱验证码验证失败: email={}, inputCode={}, cachedCode={}",
                    email, code, cacheCode);
        }

        return isValid;
    }
}
